//
//  UIImageAndBase64.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/14.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit

//图片处理根据项目要求
class UIImageAndBase64 {
    
    ///传入图片image回传对应的base64字符串,默认不带有data标识,//默认压缩到1m
    static func imageToBase64String(imageOri:UIImage,headerSign:Bool = false, maxLength: Int=1024*1024)->String?{
        if let imgData = UIImage().compressImage(image: imageOri, maxLength: maxLength) {
            let image = UIImage.init(data: imgData)
            ///根据图片得到对应的二进制编码
            guard let imageData = image?.pngData() else {
                return nil
            }
            ///根据二进制编码得到对应的base64字符串
            let base64String = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0))
            ///判断是否带有头部base64标识信息
            if headerSign {
                ///根据格式拼接数据头 添加header信息，扩展名信息
//                base64String = "data:image/png;base64," + base64String
            }
            return base64String
        }
        return ""
    }

    ///传入图片image名称回传对应的base64字符串,默认不带有data标识,
    static func imageToBase64String(imageName:String,headerSign:Bool = false)->String?{
        ///根据名称获取图片
        guard let image : UIImage = UIImage(named:imageName) else {
            return nil
        }
        return imageToBase64String(imageOri: image,headerSign:headerSign)
    }


    ///传入base64的字符串，可以是没有经过修改的转换成的以data开头的，也可以是base64的内容字符串，然后转换成UIImage
    static func base64StringToUIImage(base64String:String)->UIImage? {
        var str = base64String

        // 1、判断用户传过来的base64的字符串是否是以data开口的，如果是以data开头的，那么就获取字符串中的base代码，然后在转换，如果不是以data开头的，那么就直接转换
        if str.hasPrefix("data:image") {
            guard let newBase64String = str.components(separatedBy: ",").last else {
                return nil
            }
            str = newBase64String
        }
        // 2、将处理好的base64String代码转换成NSData
        guard let imgNSData = NSData(base64Encoded: str, options: NSData.Base64DecodingOptions()) else {
            return nil
        }
        // 3、将NSData的图片，转换成UIImage
        guard let codeImage = UIImage(data: imgNSData as Data) else {
            return nil
        }
        return codeImage
    }
}

extension UIImage {
    
    ///对指定图片进行拉伸
    func resizableImage(name: String) -> UIImage {
        
        var normal = UIImage(named: name)!
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5
        normal = resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth))
        
        return normal
    }
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func compressImage(image: UIImage, maxLength: Int) -> Data? {
        
        let newSize = self.scaleImage(image: image, imageLength: 300)
        let newImage = self.resizeImage(image: image, newSize: newSize)
        
        var compress:CGFloat = 0.9
        var data = newImage!.jpegData(compressionQuality: compress)
        
        while data!.count > maxLength && compress > 0.001 {
            compress -= 0.002
            data = newImage!.jpegData(compressionQuality: compress)
        }
        
        return data
    }
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
    func  scaleImage(image: UIImage, imageLength: CGFloat) -> CGSize {
        
        var newWidth:CGFloat = 0.0
        var newHeight:CGFloat = 0.0
        let width = image.size.width
        let height = image.size.height
    
        if (width > imageLength || height > imageLength){
            
            if (width > height) {
                
                newWidth = imageLength;
                newHeight = newWidth * height / width;
                
            }else if(height > width){
                
                newHeight = imageLength;
                newWidth = newHeight * width / height;
                
            }else{
                
                newWidth = imageLength;
                newHeight = imageLength;
            }
            
        }
        else {
            return CGSize(width: width, height: height)
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    func resizeImage(image: UIImage, newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage
    }

}
